package per.johnson.util;

import per.johnson.exception.WrongParameterException;

import java.io.*;

/**
 * Created by Johnson on 2018/9/16.
 * 文件操作工具
 */
public class FileUtil {

    private static final int BUFFER_SIZE = 2048;

    /**
     * 文件拷贝
     * @param source 源地址/文件名
     * @param dest 目标地址/文件名
     */
    public static void fileCopy(String source, String dest) throws FileNotFoundException {
        File sourceFile = new File(source);
        if(!sourceFile.exists()){
            throw new FileNotFoundException();
        }
        File destFile = new File(dest);
        try (BufferedInputStream bf = new BufferedInputStream(new FileInputStream(sourceFile)); BufferedOutputStream bo = new BufferedOutputStream(new FileOutputStream(destFile))) {
            byte[] buffer = new byte[BUFFER_SIZE];
            while (bf.read(buffer) != -1) {
                bo.write(buffer);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }  // close stream quietly

    }

    private static void showUsage(Exception e){
        System.err.println(e.getMessage());
        System.out.println("Usage： java FileUtil <source-file-name> <destination-file-name>");
    }

    private static void checkParameters(String[] args) throws WrongParameterException {
        if(args.length != 2){
            throw new WrongParameterException("Wrong parameter length!");
        }
    }

    public static void main(String[] args) {
        try {
            checkParameters(args);
            System.out.println("Starting..");
            fileCopy(args[0],args[1]);
            System.out.println("Finished..");
        }catch (WrongParameterException e){
            showUsage(e);
        } catch (FileNotFoundException e) {
            System.err.println("Wrong Source File!");
        }

    }
}
